package com.wang.http;

import com.alibaba.fastjson.JSON;
import okhttp3.*;
import okio.BufferedSink;
import okio.BufferedSource;
import okio.ByteString;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class OkHttpPostStreamExample {
    private static final OkHttpClient CLIENT = new OkHttpClient.Builder()
            .connectTimeout(5, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .build();

    public static void postAsync(String url, Map<String, Object> body, Map<String, String> headers, StreamCallback callback) {
        // 创建请求体
        RequestBody requestBody = body != null ? new RequestBody() {
            @Override
            public MediaType contentType() {
                return MediaType.get("application/json; charset=utf-8");
            }

            @Override
            public void writeTo(BufferedSink sink) throws IOException {
                sink.write(ByteString.encodeUtf8(JSON.toJSONString(body)));
            }
        } : RequestBody.create(new byte[0], null);

        // 创建Request.Builder
        Request.Builder requestBuilder = new Request.Builder()
                .url(url)
                .post(requestBody);

        // 添加请求头
        if (headers != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                requestBuilder.addHeader(entry.getKey(), entry.getValue());
            }
        }

        // 创建Request
        Request request = requestBuilder.build();

        // 发起异步请求
        CLIENT.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callback.onError(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (!response.isSuccessful()) {
                    onFailure(call, new IOException("Unexpected code " + response));
                } else {
                    try (BufferedSource source = response.body().source()) {
                        while (!source.exhausted()) {
                            String line = source.readUtf8Line();
                            callback.onReadLine(line);
                        }
                        callback.onFinished();
                    } catch (IOException e) {
                        callback.onError(e);
                    }
                }
            }
        });
    }

    public interface StreamCallback {
        void onReadLine(String line);

        void onFinished();

        void onError(IOException e);
    }



    public static void main(String[] args) {
        String url = "http://127.0.0.1:5000/stream";
//        Map<String, Object> body = Collections.singletonMap("key", "value");
//        Map<String, String> headers = Collections.singletonMap("Custom-Header", "Custom-Value");

        StreamCallback callback = new StreamCallback() {
            @Override
            public void onReadLine(String line) {
                System.out.println("Received line: " + line);
            }

            @Override
            public void onFinished() {
                System.out.println("Response finished");
            }

            @Override
            public void onError(IOException e) {
                System.out.println("Request failed: " + e.getMessage());
            }
        };

        OkHttpPostStreamExample.postAsync(url, null, null, callback);
    }

}
